package com.chat.websocket;

import com.chat.result.Result;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.*;

import java.io.IOException;

@Slf4j
@Component
@RequiredArgsConstructor
public class FriendRequestHandler implements WebSocketHandler {
    private final WebSocketSessionManager sessionManager;

    /**
     * 建立连接后
     *
     * @param session
     * @throws Exception
     */
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        // 从url后去userId,例如/websocket/friend/1
        String path = session.getUri().getPath();
        String userIdStr = path.substring(path.lastIndexOf("/") + 1);
        Integer userId = Integer.valueOf(userIdStr);

        sessionManager.addSession(userId, session);
        log.info("用户Id:{} 已连接 WebSocket", userId);
    }

    /**
     * 处理消息
     *
     * @param session
     * @param message
     * @throws Exception
     */
    @Override
    public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception {
        log.info("收到客户端消息:{}", message);
    }

    /**
     * 处理错误
     *
     * @param session
     * @param exception
     * @throws Exception
     */
    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        log.error("Websocket错误：{}", exception.getMessage());
    }

    /**
     * 连接关闭后
     *
     * @param session
     * @param closeStatus
     * @throws Exception
     */
    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
        // 断开连接时移除session
        String path = session.getUri().getPath();
        String userIdStr = path.substring(path.lastIndexOf("/") + 1);
        Integer userId = Integer.valueOf(userIdStr);

        sessionManager.removeSession(userId);
        log.info("用户Id:{} 已断开连接 WebSocket", userId);
    }

    /**
     * 支持部分消息
     *
     * @return
     */
    @Override
    public boolean supportsPartialMessages() {
        return false;
    }

    public boolean sendFriendRequest(Integer friendId) {
        // 给对方推送消息
        WebSocketSession session = sessionManager.getSession(friendId);
        if (session != null && session.isOpen()) {
            try {
                session.sendMessage(new TextMessage("你收到一条添加好友请求"));
                return true;
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        } else {
            return false;
        }
    }
}
